package cn.jbit.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2020/8/8
 */
public class AioServerHandler implements Runnable{

    CountDownLatch  countDownLatch;//保持Server进程的运行

    AsynchronousServerSocketChannel socketChannel;

    public AioServerHandler(int port) throws IOException {

        socketChannel=AsynchronousServerSocketChannel.open();

        socketChannel.bind(new InetSocketAddress(port));

        System.out.println("Aio Server start");
    }

    @Override
    public void run() {
        countDownLatch=new CountDownLatch(1);
        doAccept();
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    //attachment为我们当前句柄AioServerHandler
    public  void  doAccept(){
        socketChannel.accept(this,new AcceptCompletionHandler());
    }
}
